<!--上传-->
<template>
  <div>
    <el-upload
      ref="uploadComp"
      class="base-upload"
      name="files"
      multiple
      action
      :headers="headers"
      :show-file-list="true"
      :file-list="fileList"
      :list-type="listType"
      :show-upload-list="false"
      :accept="accept"
      :disabled="uploadLoad || disabled"
      :before-upload="beforeUpload"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :on-change="uploadVideo"
      :auto-upload="false"
      :limit="limit"
      :on-exceed="handleExceed"
    >
      <div slot="file" slot-scope="{ file }">
        <video
          :src="file.url"
          class="avatar video-avatar"
          controls="controls"
        />
        <span class="el-upload-list__item-actions">
          <span
            class="el-upload-list__item-preview"
            @click="handlePreview(file)"
          >
            <i class="el-icon-zoom-in"></i>
          </span>
          <span
            v-if="!disabled"
            class="el-upload-list__item-delete"
            @click="handleRemove(file, fileList)"
          >
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>

      <!--上传loading-->
      <div v-if="uploadLoad" v-loading="true" class="upload-loading"></div>

      <!-- 上传按钮或图标 -->
      <i v-if="listType === 'picture-card'" class="el-icon-plus"></i>
      <el-button v-else :disabled="disabled" size="small" type="primary"
        >点击上传</el-button
      >
    </el-upload>
    <!-- 上传提示 -->
    <div v-if="tip" class="tip-text">{{ tip }}</div>
    <el-dialog
      class="base-dialog"
      :custom-class="'panna-dialog_medium'"
      title="预览视频"
      :visible.sync="dialogVisible"
      append-to-body
      center
      :before-close="handleClose"
    >
      <video v-if="previewUrl" width="100%" controls="controls">
        <source :src="previewUrl" type="video/mp4" />
      </video>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { uploadVideoFile } from "../../api/Base";
import { formdataify } from "@/utils/index.js";
import { mapGetters } from "vuex";
export default {
  name: "BaseVideoUpload",
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    // 是否多选
    multiple: {
      type: Boolean,
      default: false,
    },
    // 文件类型
    accept: {
      type: String,
      default: ".mp4,.mov",
    },
    listType: {
      type: String,
      default: "text",
    },
    // 文件大小
    fileSize: {
      type: Number,
      default: 500,
    },
    // 禁用
    disabled: {
      type: Boolean,
      default: false,
    },
    tip: {
      type: String,
      default: "",
    },
    // 文件数量
    limit: {
      type: Number,
      default: 10,
    },
  },
  data() {
    return {
      uploadFile: { busiName: 32 },
      uploadLoad: false,
      headers: { Authorization: getToken() },
      fileList: [],
      isDone: false,
      dialogVisible: false,
      previewUrl: "",
    };
  },
  computed: {
    ...mapGetters(["fileDomain", "fileBucket"]),
  },
  watch: {
    value(val) {
      this.fileList = [];
      this.fileList = val;
    },
  },

  beforeDestroy() {
    this.fileList = [];
    this.$refs.uploadComp.clearFiles();
  },
  methods: {
    // 上传完成
    uploadVideo(info, fileList) {
      if (info.status === "ready") this.uploadLoad = true;
      this.beforeUpload(info);
      const obj = {
        businessType: this.businessType,
        file: info.raw,
      };
      const form = formdataify(obj);
      uploadVideoFile(form)
        .then((res) => {
          this.uploadLoad = false;
          var data = {
            storageFileName: res.data.newFileName,
            filePath: res.data.filePath,
            imgUrl: res.data.filePath,
            originalFileName: res.data.fileName,
            name: res.data.fileName,
            // url: `${this.$baseProtocol}//${this.fileDomain}/${this.fileBucket}/${res.data.filePath}`,
            url: info.url,
          };
          this.fileList.push(data);
          this.$emit("input", this.fileList);
        })
        .catch(() => {
          this.uploadLoad = false;
        });
      if (info.status === "fail") {
        this.uploadLoad = false;
        this.$message.error("上传失败");
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择${this.limit}个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    // 移除
    handleRemove(file, fileList) {
      for (let i = 0; i < fileList.length; i++) {
        if (fileList[i].uid === file.uid) {
          fileList.splice(i);
        }
      }
      this.fileList = fileList;
      this.$emit("input", this.fileList);
    },
    // 预览
    handlePreview(file) {
      const type = ["mp4", "mov"];
      const flag = type.some((item) => {
        return file.name.indexOf(item) > -1;
      });
      if (flag) {
        if (file.url) {
          this.previewUrl = file.url;
        } else {
          this.previewUrl = this.$base + file.response.data[0];
        }
        this.dialogVisible = true;
      } else {
        window.open(file.url);
      }
    },
    // 上传校验 or 大小
    beforeUpload(file) {
      var suffix = "." + file.name.split(".")[1];
      const fileTypes = this.accept.split(",");
      const checkFormat = fileTypes.includes(suffix);
      if (!checkFormat) {
        this.uploadLoad = false;
        this.$message.error(`请选择${this.accept}格式`);
      }

      const checkSize = file.size / 1024 / 1024 < this.fileSize;
      if (!checkSize) {
        this.uploadLoad = false;
        this.$message.error(`上传文件不能超过${this.fileSize}M！`);
      }

      if (!checkFormat || !checkSize) {
        var fileList = JSON.parse(JSON.stringify(this.fileList));
        this.fileList = [];
        for (var i = 0; i < fileList.length; i++) {
          this.fileList.push(fileList[i]);
        }
      }
    },
    handleClose() {
      this.previewUrl = "";
      this.dialogVisible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.base-upload {
  // height: 136px;
  position: relative;
  .upload-button {
    width: 116px;
    height: 88px;
    background: #f7f8f9;
    border-radius: 4px;
    border: 1px #dedede dashed;
    img {
      display: block;
      width: 32px;
      height: auto;
      margin: 22px auto 10px;
    }
    span {
      display: block;
      width: 100%;
      font-size: 12px;
      line-height: 12px;
      font-weight: 500;
      color: #bfbfbf;
      transform: scale(0.8);
    }
  }

  .tip-text {
    display: block;
    width: 100%;
    word-break: break-word;
    text-align: left;
    font-size: 6px;
    color: #666666;
    line-height: 18px;
    transform: scale(0.9);
  }
  .upload-loading {
    position: absolute;
    left: 0;
    top: 0;
    width: 116px;
    height: 88px;
    background-color: rgba(255, 255, 255, 0.8);
    z-index: 10;
    padding: 1px;
    box-sizing: border-box;
  }
  .no-upload {
    cursor: no-drop;
  }
}
</style>
